package it.sciuto.greetings.activities;

import it.sciuto.greetings.R;
import it.sciuto.greetings.dragger.DragController;
import it.sciuto.greetings.dragger.DragLayer;

import java.io.FileOutputStream;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class GreetingsActivity extends Activity implements View.OnLongClickListener, View.OnClickListener, View.OnTouchListener {

	// Object that sends out drag-drop events while a view is being moved.
	private DragController mDragController;
	// The ViewGroup that supports drag-drop.
	private DragLayer mDragLayer;
	// If true, it takes a long click to start the drag operation.
	// Otherwise, any touch event starts a drag.
	private boolean mLongClickStartsDrag = true;
	private static final int CHANGE_TOUCH_MODE_MENU_ID = Menu.FIRST;
	public static final int CHANGE_BACKGROUND_CODE = 100;

	private String lastSaved;

	/**
	 * onCreate - called when the activity is first created.
	 * 
	 * Creates a drag controller and sets up three views so click and long click
	 * on the views are sent to this activity. The onLongClick method starts a
	 * drag sequence.
	 * 
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mDragController = new DragController(this);

		setContentView(R.layout.greetings_layout);
		setupViews();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CHANGE_BACKGROUND_CODE) {
			System.out.print("******************** ciao");
			if (resultCode == RESULT_OK) {
				System.out.print("+++++++++++++++++ciao");
				System.out.print(data.getExtras().get("URL"));
			}
		}
	}

	/**
	 * Build a menu for the activity.
	 * 
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(0, CHANGE_TOUCH_MODE_MENU_ID, 0, "Change Touch Mode");
		return true;
	}

	/**
	 * Handle a click on a view. Tell the user to use a long click (press).
	 * 
	 */

	public void onClick(View v) {
		if (mLongClickStartsDrag) {
			// Tell the user that it takes a long click to start dragging.
			toast("Press and hold to drag an image.");
		}
	}

	/**
	 * Handle a long click. If mLongClick only is true, this will be the only
	 * way to start a drag operation.
	 * 
	 * @param v
	 *            View
	 * @return boolean - true indicates that the event was handled
	 */

	public boolean onLongClick(View v) {
		if (mLongClickStartsDrag) {

			// trace ("onLongClick in view: " + v + " touchMode: " +
			// v.isInTouchMode ());

			// Make sure the drag was started by a long press as opposed to a
			// long click.
			// (Note: I got this from the Workspace object in the Android
			// Launcher code.
			// I think it is here to ensure that the device is still in touch
			// mode as we start the drag operation.)
			if (!v.isInTouchMode()) {
				toast("isInTouchMode returned false. Try touching the view again.");
				return false;
			}
			return startDrag(v);
		}

		// If we get here, return false to indicate that we have not taken care
		// of the event.
		return false;
	}

	/**
	 * Perform an action in response to a menu item being clicked.
	 * 
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case CHANGE_TOUCH_MODE_MENU_ID:
			mLongClickStartsDrag = !mLongClickStartsDrag;
			String message = mLongClickStartsDrag ? "Changed touch mode. Drag now starts on long touch (click)." : "Changed touch mode. Drag now starts on touch (click).";
			Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * This is the starting point for a drag operation if mLongClickStartsDrag
	 * is false. It looks for the down event that gets generated when a user
	 * touches the screen. Only that initiates the drag-drop sequence.
	 * 
	 */
	public boolean onTouch(View v, MotionEvent ev) {
		// If we are configured to start only on a long click, we are not going
		// to handle any events here.
		if (mLongClickStartsDrag)
			return false;

		boolean handledHere = false;

		final int action = ev.getAction();

		// In the situation where a long click is not needed to initiate a drag,
		// simply start on the down event.
		if (action == MotionEvent.ACTION_DOWN) {
			handledHere = startDrag(v);
		}

		return handledHere;
	}

	/**
	 * Start dragging a view.
	 * 
	 * */
	public boolean startDrag(View v) {
		Object dragInfo = v;
		mDragController.startDrag(v, mDragLayer, dragInfo, DragController.DRAG_ACTION_MOVE);
		return true;
	}

	/**
	 * Finds all the views we need and configure them to send click events to
	 * the activity.
	 * 
	 */
	private void setupViews() {
		final DragLayer dl = (DragLayer) findViewById(R.id.drag_layer);
		dl.setBackgroundResource(R.drawable.easter_bunny);

		DragController dragController = mDragController;

		mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
		mDragLayer.setDragController(dragController);
		dragController.addDropTarget(mDragLayer);

		ImageView i1 = new ImageView(this);
		ImageView i2 = new ImageView(this);
		ImageView i3 = new ImageView(this);

		i1.setImageResource(R.drawable.egg_green);
		i1.setOnClickListener(this);
		i1.setOnLongClickListener(this);
		i1.setOnTouchListener(this);
		dl.addView(i1);

		i2.setImageResource(R.drawable.egg_blue);
		i2.setOnClickListener(this);
		i2.setOnLongClickListener(this);
		i2.setOnTouchListener(this);
		dl.addView(i2);

		i3.setImageResource(R.drawable.egg_red);
		i3.setOnClickListener(this);
		i3.setOnLongClickListener(this);
		i3.setOnTouchListener(this);
		dl.addView(i3);

		TextView tv = new TextView(this);
		tv.setText("Tantissimi Auguri!");
		tv.setOnLongClickListener(this);
		tv.setOnTouchListener(this);
		dl.addView(tv);

		String message = mLongClickStartsDrag ? "Press and hold to start dragging." : "Touch a view to start dragging.";
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();

		ImageButton saveButton = (ImageButton) findViewById(R.id.save_button);
		saveButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				lastSaved = "/sdcard/criminal/" + setFileName();
				saveBitmap(loadBitmapFromView(dl), lastSaved);
			}
		});

		ImageButton shareButton = (ImageButton) findViewById(R.id.share_button);
		shareButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				saveBitmap(loadBitmapFromView(dl), "/sdcard/greetings/shared.jpg");
				share();
			}
		});

		ImageButton changeBackgroundButton = (ImageButton) findViewById(R.id.background_button);
		changeBackgroundButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				Intent myIntent = new Intent(getBaseContext(), BackgroundDialogActivity.class);
				startActivityForResult(myIntent, CHANGE_BACKGROUND_CODE);
			}
		});

	}

	/**
	 * @return
	 */
	private CharSequence setFileName() {
		Date d = new Date();
		return DateFormat.format("ddMMyyyy_hhmmss", d.getTime()) + ".jpg";
	}

	/**
	 * Show a string on the screen via Toast.
	 * 
	 * @param msg
	 *            String
	 * @return void
	 */

	public void toast(String msg) {
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
	}

	/**
	 * @param bmp
	 * @param filename
	 */
	public void saveBitmap(Bitmap bmp, String filename) {
		try {
			FileOutputStream out = new FileOutputStream(filename);
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
			out.flush();
			out.close();
			bmp.recycle();
			Toast.makeText(this, R.string.save_ok, Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, R.string.save_error, Toast.LENGTH_LONG).show();
		}

	}

	/**
	 * 
	 */
	public void share() {
		Intent share = new Intent(Intent.ACTION_SEND);
		share.setType("image/jpeg");
		share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/greetings/shared.jpg"));
		startActivity(Intent.createChooser(share, getString(R.string.share_title)));
	}

	/**
	 * @param v
	 * @return
	 */
	public Bitmap loadBitmapFromView(View v) {
		v.setDrawingCacheEnabled(true);
		Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
		v.setDrawingCacheEnabled(false);
		return b;
	}

}
